package com.zhilifang.modules.sys.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Constants;
import com.zhilifang.common.utils.R;
import com.zhilifang.common.utils.ShiroUtils;
import com.zhilifang.common.validator.ValidatorUtils;
import com.zhilifang.common.validator.group.AddGroup;
import com.zhilifang.modules.sys.entity.RegisterUser;
import com.zhilifang.modules.sys.entity.SysUserEntity;
import com.zhilifang.modules.sys.service.SysUserService;

@RestController
public class RegisterController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;

	@PostMapping("/sys/register")
	public R register(@RequestBody RegisterUser user) {
			ValidatorUtils.validateEntity(user, AddGroup.class);
			
			String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
			
			System.out.println("user" +user);
			String captcha=user.getCaptcha();
			if (!captcha.equalsIgnoreCase(kaptcha)) {
				return R.error("验证码不正确");
			}
			
			Long count = sysUserService.countByUserName(user.getUsername());
			if(count>0){
				return R.error("用户已存在!");
			}
			
			//json to str
			String jsonString = JSON.toJSONString(user);
			
			//str to  javaBean
			SysUserEntity se = JSON.parseObject(jsonString, SysUserEntity.class);
			
			//se.setCreateUserId(getUserId());
			System.out.println(se);
			sysUserService.register(se);
		return R.ok("注册成功!").put("code", 0);
	}

}
